package com.iqiyi.pps.epg.api.utils;

import com.iqiyi.kiwi.utils.EncodeUtils;
import com.iqiyi.kiwi.utils.JsonBinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 从支付中心项目代码迁移过来的用户接口参数校验的工具类
 * User: lishunlong
 * Date: 12-8-30
 * Time: 下午4:25
 * To change this template use File | Settings | File Templates.
 */
public class WebUtils {
    public static final Logger logger = LoggerFactory.getLogger(WebUtils.class);
    /**
     * 对map进行签名
     *
     * @param params 参数
     * @param key    密钥
     * @param filterList    需要从参数列表中过滤掉的参数
     * @return 签名串
     */
    public static String signMessageRequest(Map<String, String> params, String key, List<String> filterList) {
        Map<String, String> map = paraFilter(params, filterList);
        //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        String prestr = createLinkString(map);
        //把拼接后的字符串再与安全校验码直接连接起来
        prestr = prestr + key;
        String charset = params.get("charset");
        logger.info("sign:" + prestr);
        return EncodeUtils.MD5(prestr, charset);
    }

    /**
     * 对map进行签名
     *
     * @param params 参数
     * @param key    密钥
     * @param filterList    需要从参数列表中过滤掉的参数
     * @return 签名串
     */
    public static String signMessageRequestNew(Map<String, String> params, String key, String charset, List<String> filterList) {
        Map<String, String> map = paraFilter(params, filterList);
        //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        String prestr = createLinkString(map);
        //把拼接后的字符串再与安全校验码直接连接起来
        prestr = prestr + key;
        logger.info("sign:" + prestr);
        return EncodeUtils.MD5(prestr, charset);
    }

    /**
     * 对map进行签名
     *
     * @param params 参数
     * @param key    密钥
     * @param filters    需要从参数列表中过滤掉的参数
     * @return 签名串
     */
    public static String signMessageRequest(Map<String, String> params, String key, String... filters) {
        List<String> filterList = Arrays.asList(filters);
        return signMessageRequest(params, key, filterList);
    }

    /**
     * 功能：除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    private static Map paraFilter(Map sArray, List<String> filterList) {
        List keys = new ArrayList(sArray.keySet());
        Map sArrayNew = new HashMap();

        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            String value = (String) sArray.get(key);

            if (value == null || value.equals("") || filterList.contains(key)) {
                continue;
            }
            sArrayNew.put(key, value);
        }

        return sArrayNew;
    }


    /**
     * 功能：把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map params) {
        List keys = new ArrayList(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            String value = (String) params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    /**
     * 获得POST 过来参数设置到新的params中
     * @param requestParams
     * 			POST 过来参数Map
     * @return
     * 			新的Map
     */
    public static Map<String, String> genMapByRequestParas(Map requestParams){
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        return params;
    }

    public static boolean isResponseSuccess(String res){
       Map<String,String> mRes =  JsonBinder.buildNormalBinder().fromJson(res,HashMap.class);
       return (mRes!=null)&&("A00000".equals(mRes.get("code")));
    }

    public static String getResponseContent(String res) {
        Map mRes = JsonBinder.buildNormalBinder().fromJson(res, HashMap.class);
        if (mRes == null) {
            return null;
        }
        if ("A00000".equals(mRes.get("code"))) {
            return JsonBinder.buildNormalBinder().toJson(mRes.get("data"));
        }
        return mRes.get("code") + ":" + mRes.get("msg");
    }
}
